package com.xiaofan.sql

import com.xiaofan.apitest.source.SensorReading
import org.apache.flink.streaming.api.scala._
import org.apache.flink.table.api._
import org.apache.flink.table.api.bridge.scala.StreamTableEnvironment

object Example {
  def main(args: Array[String]): Unit = {

    val env: StreamExecutionEnvironment = StreamExecutionEnvironment.getExecutionEnvironment
    env.setParallelism(1)

    val inputPath = "D:\\big-data\\code\\FlinkTutorial\\src\\main\\resources\\sensor.txt"
    val inputStream: DataStream[String] = env.readTextFile(inputPath)

    val dataStream: DataStream[SensorReading] = inputStream.map(
      data => {
        val arr: Array[String] = data.split(",")
        SensorReading(arr(0), arr(1).toLong, arr(2).toDouble)
      }
    )

    val tabEnv: StreamTableEnvironment = StreamTableEnvironment.create(env)

    val dataTable: Table = tabEnv.fromDataStream(dataStream)

    // val resultTable: Table = dataTable
    //  .select($"id", $"temperature")
    //  .filter($"id" === "sensor_1")

    tabEnv.createTemporaryView("dataTable", dataTable)

    val resultTable: Table = tabEnv.sqlQuery(
      """
        |select id, temperature from dataTable where id = 'sensor_1'
        |""".stripMargin)

    tabEnv.toAppendStream[(String, Double)](resultTable).print("sql")
    tabEnv.executeSql()

    env.execute("table api and sql test")

  }
}
